/*
* 包含n个action creatoe
* 异步action
* 同步action*/
//websocket发送聊天数据
import io from 'socket.io-client'

import {AUTH_Success,ERROR_MSG,RECEIVE_USER,
    RESET_USER,RECEIVE_USERLIST,
    RECEIVE_CHATMSGLIST,
    RECEIVEANMSG,
    MSGREAD
} from './action-types'
import {reqLogin,reqRegister,reqUpdate,reqUser,reqUesrList,reqChatMsg,readMsg} from '../api'


//授权成功的同步action
const auth_success =(user)=>({type:AUTH_Success,data:user})
//错误提示信息的action
const errormsg =(msg)=>({type:ERROR_MSG,data:msg})
//接收用户的同步action
const receiveUser = (user)=>({type:RECEIVE_USER,data:user})
//重置用户的异步action
//当用户登录之后删除了cookie
export const resetUser =(msg)=> ({type:RESET_USER,data:msg})
//接收到用户列表的同步action
export const receiveUserList =(userlist)=>({type:RECEIVE_USERLIST,data:userlist})
//接收消息列表的同步action
export const receiveMsgList  =({users,chatMsgs,current_userid}) =>({type:RECEIVE_CHATMSGLIST,data:{users,chatMsgs,current_userid}})
//接收到一条消息的同步action
export const receive_an_msg = ({chat_msg,current_userid})=>({type:RECEIVEANMSG,data:{chat_msg,current_userid}})
//更新已读消息的同步actiomn
const MsgRead = ({from,to,readcount}) =>({type:MSGREAD,data:{from,to,readcount}})

//建立对服务器的绑定和监听
function initIO(current_userid,dispatch) {
//单例对象
    if (!io.socket){
        io.socket = io("ws://localhost:4000")
        io.socket.on("receiveMsg",chat_msg=>{
            console.log("收到服务器发来的数据",chat_msg);
            //由于服务器收到消息之后是向所有的客户端都发送一遍，
            //收到数据之后进行判断，看是否是属于当前用户的消息
            if (chat_msg.from===current_userid||chat_msg.to===current_userid){
                dispatch(receive_an_msg({chat_msg,current_userid}))
            }
        })
    }
}

//注册异步action
export const register =(user)=>{
    const {username,password,type} = user
    //前台验证
    if (!username){
        return errormsg('用户名不能为空')
    }
    if (password!=user.password2){
        return errormsg('两次密码不一致')
    }
    //数据前台验证通过
    return async dispatch=>{
        //发送异步请求
        /*const promise =reqRegister(user)
        promise.then(response=>{
            const result = response.data
        })*/
        const response = await reqRegister(user)
        const result = response.data
        //调试
        console.log('result',result)
        if (result.code===0){
            //成功
            //分发成功的action
            getChatMsg(result.data._id,dispatch)
            dispatch(auth_success(result.data))
        }else{
            //失败
            dispatch(errormsg(result.msg))
        }
    }
}
//登录异步action
export const login =(user)=>{
    const {username,password} = user
    //前台验证
    if (!username){
        return errormsg('用户名不能为空')
    }
    if (!password){
        return errormsg('密码不能为空')
    }
    //数据前台验证通过
    return async dispatch=>{
        //发送异步请求
        /*const promise =reqRegister(user)
        promise.then(response=>{
            const result = response.data
        })*/
        const response = await reqLogin(user)
        const result = response.data
        if (result.code===0){
            //成功
            //分发成功的action
            getChatMsg(result.data._id,dispatch)
            dispatch(auth_success(result.data))
        }else{
            //失败
            dispatch(errormsg(result.msg))
        }
    }
}
//异步更新用户的action
export const Update = (user)=>{
    return async dispatch=>{
        //发送请求更新数据
        const response = await reqUpdate(user)
        const result = response.data
        if (result.code===0){
    //更新数据成功，分发action
    dispatch(receiveUser(result.data))
    }else{
        dispatch(resetUser(result.msg))
            }
        }
}
//主页面最开始获取用户的异步action
export const getUser= ()=>{
    return async dispatch=>{
      //发送请求请求user
        const  response = await reqUser()
        const result = response.data
        if (result.code==0){
            //成功得到数据
            getChatMsg(result.data._id,dispatch)
            dispatch(receiveUser(result.data))
        }else{
            dispatch(resetUser(result.msg))
        }

    }
}

//获取用户列表的异步action
export const getUserList=(type)=>{
    return async dispatch=>{
        //发送请求获取用户列表
        const response = await reqUesrList(type)
        const result = response.data
        //请求成功分发同步action
        if (result.code===0){
            dispatch(receiveUserList(result.data))
        }
    }
}

//发送消息的action,这个是用websocket方式进行的，不需要ajax
export const sendMsg=({from,to,content})=>{
    return dispatch=>{
        console.log("发送消息",{from,to,content})
        //initIO()
        io.socket.emit("sendMsg",{from,to,content})
    }
}
//获取用户所有相关聊天数据的异步action
//这个函数有三个执行的场景，用户注册成功，用户登录，用户自动登录
async function getChatMsg(current_userid,dispatch) {
    initIO(current_userid,dispatch)
    const response= await reqChatMsg()
    const {chatMsgs,users} = response.data.data
    //测试
    //console.log("请求回来的消息列表",response.data)
    //console.log("请求回来的消息列表2",{chatMsgs,users})

    //分发同步action
    if(response.data.code===0){
        dispatch(receiveMsgList({users,chatMsgs,current_userid}))
    }
}
//更新已读消息的异步action
export const UpdateReadMsg=({from,to})=> {
    //

    return async dispatch =>{
        console.log("红红火火恍恍惚惚"+from+to)
        const response = await readMsg(from)
        console.log("测试---------",response.data)
        if (response.data.code===0){
            //分发action
            const readcount = response.data.data
            dispatch(MsgRead({from,to,readcount}))
        }
    }
}